/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.unicode.unihan.loader;

import java.io.FileNotFoundException;
import java.io.InputStream;
import org.geergenbein.dao.DAOUtils;
import org.unicode.unihan.dao.UnihanRowDAO;
import org.unicode.unihan.domain.UnihanRow;
import org.geergenbein.parser.DocumentParser;
import org.unicode.unihan.parser.UnihanLineParser;

/**
 *
 * @author andrew
 */
public class RowLoader {

    private final static int TRANSACTION_SIZE = 100;

    public void load(InputStream is) {
        DocumentParser<UnihanRow> parser = new DocumentParser(is,
                new UnihanLineParser());
        load(parser);
    }

    /**
     * Iterate through the Unihan data and insert it into the database
     */
    public void load(String path) throws FileNotFoundException {
        DocumentParser<UnihanRow> parser = new DocumentParser(path,
                new UnihanLineParser());
        load(parser);
    }

    private void load(DocumentParser<UnihanRow> parser) {
        UnihanRowDAO unihanRowDAO = DAOUtils.getInstance().getUnihanRowDAO();
        int count = 0;
        DAOUtils.getInstance().getTransaction().begin();
        for (UnihanRow unihanRow : parser) {
            unihanRowDAO.makePersistent(unihanRow);
            if (count++ % TRANSACTION_SIZE == 0) {
                DAOUtils.getInstance().getTransaction().commit();
                unihanRowDAO.clear();
                DAOUtils.getInstance().getTransaction().begin();
            }
        }
        DAOUtils.getInstance().getTransaction().commit();
    }
}
